<?php

namespace App\Http\Controllers\Admin;
//session_start();
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;
use Cache;

use Intervention\Image\ImageManagerStatic as Image;

class ProductController extends Controller
{
    /**
     * 商品列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //echo 'product list page';
        //$product=DB::table('product')->select('product_id','title','keyword','sprice','rtime','sellnum','logo_pic','new_recommended','hotsell_recommended','boutique_recommended','disabled')->get();
        //return view('admin/product/product/index',['product'=>$product]);
        //var_dump($request);
        
         $data = DB::table('product')->where(function($query) use ($request){
            if($request->input('disabled')){
                $d=$request->input('disabled');
            }else{
                $d=1;
            }
                $query->where('disabled',$d)
                ->where('keyword','like','%'.$request->input('keywords').'%');
           })->paginate($request->input('num',5));
        // dd($data);
        return view('admin/product/product/index',['data' => $data,'request'=>$request->all()]);

    }

    

    /**
     * 添加商品
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //人群缓存
        if(!Cache::has('crowds'))
        {
            $crowds=DB::table('crowd')->get();
            Cache::forever('crowds',$crowds);
        }
        $crowds=Cache::get('crowds');
        //运动缓存
        if(!Cache::has('sports'))
        {
            $sports=DB::table('sport')->get();
            Cache::forever('sports',$sports);
        }
        $sports=Cache::get('sports');
        //品牌缓存
        if(!Cache::has('brands'))
        {
            $brands=DB::table('brand')->select('brand_id','brand_logo','brand_pro_code')->get();
            Cache::put('brands',$brands,2);
        }
        $brands=Cache::get('brands');
        //男子包含运动缓存下拉列表
        if(!Cache::has('msports_str'))
        {
            $msports_id=DB::table('cro_spo_rel')->where('cro_id','=','1')->lists('spo_id');
            $msports=DB::table('sport')->whereIn('sport_id',$msports_id)->select('sport_id','sport_type')->get();
            $msports_str='';
            foreach($msports as $msport){
                $every_msport='<option value="'.$msport->sport_id.'">'.$msport->sport_type.'</option>';
                $msports_str.=$every_msport;
            }
            Cache::forever('msports_str',$msports_str);
        }
        $msports_str=Cache::get('msports_str');
        //女子包含运动缓存下拉列表
        if(!Cache::has('wsports_str'))
        {
            $wsports_id=DB::table('cro_spo_rel')->where('cro_id','=','2')->lists('spo_id');
            $wsports=DB::table('sport')->whereIn('sport_id',$wsports_id)->select('sport_id','sport_type')->get();
            $wsports_str='';
            foreach($wsports as $wsport){
                $every_wsport='<option value="'.$wsport->sport_id.'">'.$wsport->sport_type.'</option>';
                $wsports_str.=$every_wsport;
            }
            Cache::forever('wsports_str',$wsports_str);
        }
        $wsports_str=Cache::get('wsports_str');
        //儿童包含运动缓存下拉列表
        if(!Cache::has('csports_str'))
        {
            $csports_id=DB::table('cro_spo_rel')->where('cro_id','=','3')->lists('spo_id');
            $csports=DB::table('sport')->whereIn('sport_id',$csports_id)->select('sport_id','sport_type')->get();
            $csports_str='';
            foreach($csports as $csport){
                $every_csport='<option value="'.$csport->sport_id.'">'.$csport->sport_type.'</option>';
                $csports_str.=$every_csport;
            }
            Cache::forever('csports_str',$csports_str);
        }
        $csports_str=Cache::get('csports_str');
        //var_dump($msports_str);
        //var_dump($wsports_str);
        //var_dump($csports_str);
        return view('admin/product/product/create',['crowds'=>$crowds,'msports_str'=>$msports_str,'wsports_str'=>$wsports_str,'csports_str'=>$csports_str,'brands'=>$brands]);
    }

    /**
     * 处理添加商品
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $inputs=$request->except(['_token']);
        //var_dump($inputs);
        $this->validate($request,[
            'title'=>'required|min:4|max:20',
            'mprice'=>'required|numeric',
            'sprice'=>'required|numeric',
            'lprice'=>'numeric',
            'logo_pic'=>'required|image',
            'ad_pic'=>'image'
        ],[
            'title.required'=>'商品标题不能为空',
            'title.min'=>'商品标题长度必须4-20字符',
            'title.max'=>'商品标题长度必须4-20字符',
            'mprice.required'=>'市场价不能为空',
            'sprice.required'=>'商城价不能为空',
            'logo_pic.required'=>'LOGO图片不能为空',
            'image'=>'必须上传图片',
            'numeric'=>'价格必须数字'
        ]);
        //查询生成crspr_id
        $crspr_id=DB::table('cro_spo_rel')->where('cro_id','=',$inputs['cro_id'])->where('spo_id','=',$inputs['spo_id'])->value('crspr_id');
        //var_dump($crspr_id);

        //人群信息
        $this_crowd=DB::table('crowd')->where('crowd_id','=',$inputs['cro_id'])->first();
        //var_dump($this_crowd->crowd_type);
        //var_dump($this_crowd->crowd_pro_code);
        //运动信息
        $this_sport=DB::table('sport')->where('sport_id','=',$inputs['spo_id'])->first();
        //var_dump($this_sport->sport_type);
        //var_dump($this_sport->sport_pro_code);
        //品牌信息
        $this_brand=DB::table('brand')->where('brand_id','=',$inputs['brand_logo'])->first();
        //var_dump($this_brand->brand_name_zh);
        //var_dump($this_brand->brand_pro_code);

        //拼接关键字
        $keyword=$this_brand->brand_name_zh.$this_crowd->crowd_type.$this_sport->sport_type.'鞋';
        //var_dump($keyword);

        //拼接前置商品编号
        $pre_pro_code=$this_crowd->crowd_pro_code.$this_sport->sport_pro_code.$this_brand->brand_pro_code;
        //var_dump($pre_pro_code);

        //
        if($request->file('logo_pic')->isValid())
        {
            $logo_filename=time().rand(1000,9999);
            $logo_ext=$request->file('logo_pic')->getClientOriginalExtension();
            $logo_basename=$logo_filename.'.'.$logo_ext;
            $request->file('logo_pic')->move('uploads/product/logo_pic',$logo_basename);
            //等比缩放
            $fname='uploads/product/logo_pic/'.$logo_basename;
            //var_dump($fname);
            $srcarr = getimagesize($fname);
            //var_dump($srcarr);
            $w=100;
            $h=100;
            if($w/$srcarr[0]>$h/$srcarr[1]){
                $bili = $h/$srcarr[1];
            }else{
                $bili = $w/$srcarr[0];
            }
            $nw = floor($srcarr[0]*$bili);
            $nh = floor($srcarr[1]*$bili);
            $img = Image::make($fname)->resize($nw,$nh)->save($fname);//缩放
            //var_dump($img);
        }
        $ad_basename='';
        if($request->file('ad_pic')){
            if($request->file('ad_pic')->isValid())
            {
                $ad_filename=time().rand(1000,9999);
                $ad_ext=$request->file('ad_pic')->getClientOriginalExtension();
                $ad_basename=$ad_filename.'.'.$ad_ext;
                $request->file('ad_pic')->move('uploads/product/ad_pic',$ad_basename);
            }
            //等比缩放
            $fname='uploads/product/ad_pic/'.$ad_basename;
            //var_dump($fname);
            $srcarr = getimagesize($fname);
            //var_dump($srcarr);
            $w=300;
            $h=300;
            if($w/$srcarr[0]>$h/$srcarr[1]){
                $bili = $h/$srcarr[1];
            }else{
                $bili = $w/$srcarr[0];
            }
            $nw = floor($srcarr[0]*$bili);
            $nh = floor($srcarr[1]*$bili);
            $img = Image::make($fname)->resize($nw,$nh)->save($fname);
            //var_dump($ad_basename);
        }
        //var_dump($logo_basename);
        //var_dump($ad_basename);

        $rtime=time();
        //插入
        //var_dump($inputs);
        $new_pro_id=DB::table('product')->insertGetId(['crspr_id'=>$crspr_id,'brand_id'=>$inputs['brand_logo'],'title'=>$inputs['title'],'description'=>$inputs['description'],'mprice'=>$inputs['mprice'],'sprice'=>$inputs['sprice'],'lprice'=>$inputs['lprice'],'rtime'=>$rtime,'logo_pic'=>$logo_basename,'ad_pic'=>$ad_basename,'new_recommended'=>$inputs['new_recommended'],'keyword'=>$keyword,'pre_pro_code'=>$pre_pro_code]);
        //var_dump('ok');
        return redirect()->route('createattr',[$new_pro_id]);
        
    }

    /**
     * 商品详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        Cache::flush();
    }

    /**
     * 更改商品
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //var_dump($id);
        $data=DB::table('product')->where('product_id','=',$id)->first();
        //var_dump($data);
        $commentnum=$data->commentnum;
        $total_score=$data->total_score;
        if($commentnum==0)
        {
            $score='无评价';
        }else{
            $score=round($total_score/$commentnum).'%';
        }
        //属性
        // $attrdata=DB::table('pro_attr')->where('pro_id','=',$id)->get();
        // var_dump($attrdata);
        // $cosir_id_arr=array();
        // $suf_pic_arr=array();
        // foreach($attrdata as $attrvalue){
        //     $cosir_id_arr[]=$attrvalue->cosir_id;
        //     $suf_pic_arr[]=$attrvalue->suf_pic;
        // }
        // var_dump($cosir_id_arr);
        // //色系
        // $col_id_arr=DB::table('col_siz_rel')->whereIn('cosir_id',$cosir_id_arr)->lists('col_id');
        // var_dump($col_id_arr);
        // $col_id_arr=array_unique($col_id_arr);
        // var_dump($col_id_arr);
        // $color_arr=DB::table('color')->whereIn('color_id',$col_id_arr)->lists('color_hex_code');
        // var_dump($color_arr);

        // //轮播图片
        // //var_dump($suf_pic_arr);
        // $suf_pic_arr=array_unique($suf_pic_arr);
        // var_dump($suf_pic_arr);

        

        return view('admin/product/product/edit',['data'=>$data,'score'=>$score]);
    }

    /**
     * 处理更改商品
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $inputs=$request->except(['_token','_method']);
        //var_dump($inputs);
        $this->validate($request,[
            'title'=>'required|min:4|max:20',
            'mprice'=>'required|numeric',
            'sprice'=>'required|numeric',
            'lprice'=>'numeric'        
        ],[
            'title.required'=>'商品标题不能为空',
            'title.min'=>'商品标题长度必须4-20字符',
            'title.max'=>'商品标题长度必须4-20字符',
            'mprice.required'=>'市场价不能为空',
            'sprice.required'=>'商城价不能为空',
            'numeric'=>'价格必须数字'
        ]);
        if($request->hasFile('logo_pic')){
            if($request->file('logo_pic')->isValid())
            {
                $logo_filename=time().rand(1000,9999);
                $logo_ext=$request->file('logo_pic')->getClientOriginalExtension();
                $logo_basename=$logo_filename.'.'.$logo_ext;
                $request->file('logo_pic')->move('uploads/product/logo_pic',$logo_basename);
                //等比缩放
                $fname='uploads/product/logo_pic/'.$logo_basename;
                //var_dump($fname);
                $srcarr = getimagesize($fname);
                //var_dump($srcarr);
                $w=100;
                $h=100;
                if($w/$srcarr[0]>$h/$srcarr[1]){
                    $bili = $h/$srcarr[1];
                }else{
                    $bili = $w/$srcarr[0];
                }
                $nw = floor($srcarr[0]*$bili);
                $nh = floor($srcarr[1]*$bili);
                $img = Image::make($fname)->resize($nw,$nh)->save($fname);//缩放
                //var_dump($img);
                if(file_exists('./uploads/product/logo_pic/'.$inputs['old_logo_pic'])){
                    unlink('./uploads/product/logo_pic/'.$inputs['old_logo_pic']);
                }
            }   
        }else{
            $logo_basename=$inputs['old_logo_pic'];
        }
        //var_dump($logo_basename);

        if($request->hasFile('ad_pic')){
            if($request->file('ad_pic')->isValid())
            {
                $ad_filename=time().rand(1000,9999);
                $ad_ext=$request->file('ad_pic')->getClientOriginalExtension();
                $ad_basename=$ad_filename.'.'.$ad_ext;
                $request->file('ad_pic')->move('uploads/product/ad_pic',$ad_basename);
                //等比缩放
                $fname='uploads/product/ad_pic/'.$ad_basename;
                //var_dump($fname);
                $srcarr = getimagesize($fname);
                //var_dump($srcarr);
                $w=300;
                $h=300;
                if($w/$srcarr[0]>$h/$srcarr[1]){
                    $bili = $h/$srcarr[1];
                }else{
                    $bili = $w/$srcarr[0];
                }
                $nw = floor($srcarr[0]*$bili);
                $nh = floor($srcarr[1]*$bili);
                $img = Image::make($fname)->resize($nw,$nh)->save($fname);//缩放
                //var_dump($img);
                 if($inputs['old_ad_pic']!=''){
                    if(file_exists('./uploads/product/ad_pic/'.$inputs['old_ad_pic'])){
                    unlink('./uploads/product/ad_pic/'.$inputs['old_ad_pic']);
                    }
                }

            }   
        }else{
            $ad_basename=$inputs['old_ad_pic'];
        }
        //var_dump($ad_basename);
        DB::table('product')->where('product_id',$id)->update(['title'=>$inputs['title'],'description'=>$inputs['description'],'mprice'=>$inputs['mprice'],'sprice'=>$inputs['sprice'],'lprice'=>$inputs['lprice'],'new_recommended'=>$inputs['new_recommended'],'hotsell_recommended'=>$inputs['hotsell_recommended'],'boutique_recommended'=>$inputs['boutique_recommended'],'disabled'=>$inputs['disabled'],'logo_pic'=>$logo_basename,'ad_pic'=>$ad_basename]);

        return redirect('admin/product')->with('add_pro_success','更改商品成功');
    }
}
